﻿/****************
* Creat Date: 2020/08/04 03:55:26
* Creator: Quick.CodeGenerator
*****************/
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using BookStores.Entity;
using System.Threading.Tasks;
using QuickFramework.SqlSugarOrm;
using SqlSugar;
using Utility.Extensions;

namespace BookStores.Repositories
{
    /// <summary>
    /// 数据表操作实体类：GoodsTag
    /// </summary>
    [Serializable]
    public partial class GoodsTagRepository : QuickFramework.SqlSugarOrm.Repository<BookStores.Entity.GoodsTag>, BookStores.Contracts.IGoodsTagRepository
    {
        /// <summary>
        /// 构造方法,初始化数据库链接：GoodsTag
        /// </summary>
        public GoodsTagRepository() : base(QuickFramework.SqlSugarOrm.DbConnectionStrings.Default)
        { }
        /// <summary>
        /// 构造方法,初始化数据库链接：GoodsTag
        /// </summary>
        public GoodsTagRepository(string dbConnectionString) : base(dbConnectionString)
        { }

        /// <summary>
        /// 添加不存在的数据
        /// </summary>
        /// <param name="tags">标签列表</param>
        /// <param name="type">标签类型</param>
        /// <returns></returns>
        public async Task<bool> AddNotExists(string[] tags, string type)
        {
            using (IUnitOfWork unitOfWork = new UnitOfWork().CreateUoW(base.ConnectionStringName))
            {
                try
                {
                    for (int i = 0; i < tags.Length; i++)
                    {
                        var tag = tags[i];
                        bool isExists = await base.Queryable(unitOfWork).CountAsync(t => 
                                                                        string.Equals(t.Tag_Type, type.Trim(), StringComparison.OrdinalIgnoreCase)
                                                                        && string.Equals(t.Tag, tag.Trim(), StringComparison.OrdinalIgnoreCase)) > 0;
                        if (!isExists)
                        {
                            BookStores.Entity.GoodsTag tagModel = new GoodsTag();
                            tagModel.ID = tagModel.NewKey;
                            tagModel.Tag_Type = type.StrTrim();
                            tagModel.Tag = tags[i].StrTrim();
                            _ = await base.Insertable(tagModel, unitOfWork).ExecuteCommandAsync();
                        }
                    }
                    unitOfWork.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                }
                return false;
            }
        }
    }
}
